package com.example.demo1.service;

import com.example.demo1.pojo.dto.orderCreateDto;
import com.example.demo1.pojo.dto.orderUpdateDto;
import com.example.demo1.pojo.order;
import com.example.demo1.pojo.product;
import com.example.demo1.pojo.user;
import com.example.demo1.repository.orderRepository;
import com.example.demo1.repository.productRepository;
import com.example.demo1.repository.userRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class orderService {
    @Autowired
    private orderRepository repository;

    @Autowired
    private userRepository userRepository;

    @Autowired
    private productRepository productRepository;

    @Transactional
    public order createOrder(orderCreateDto orderDto) {
        Optional<user> userOpt = userRepository.findById(orderDto.getUserId());
        if (!userOpt.isPresent()) {
            throw new RuntimeException("用户不存在");
        }

        Optional<product> productOpt = productRepository.findById(orderDto.getProductId());
        if (!productOpt.isPresent()) {
            throw new RuntimeException("商品不存在");
        }

        product product = productOpt.get();
        if (product.getStatus() != 1) {
            throw new RuntimeException("商品已下架");
        }

        if (product.getStock() < orderDto.getQuantity()) {
            throw new RuntimeException("商品库存不足");
        }

        String orderNumber = generateOrderNumber();

        BigDecimal unitPrice = product.getPrice();
        BigDecimal totalAmount = unitPrice.multiply(new BigDecimal(orderDto.getQuantity()));
        BigDecimal shippingFee = calculateShippingFee(product.getWeight(), orderDto.getQuantity());
        BigDecimal paymentAmount = totalAmount.add(shippingFee);

        order order = new order();
        order.setOrderNumber(orderNumber);
        order.setUserId(orderDto.getUserId());
        order.setProductId(orderDto.getProductId());
        order.setQuantity(orderDto.getQuantity());
        order.setUnitPrice(unitPrice);
        order.setTotalAmount(totalAmount);
        order.setShippingFee(shippingFee);
        order.setPaymentAmount(paymentAmount);
        order.setShippingAddress(orderDto.getShippingAddress());
        order.setReceiverName(orderDto.getReceiverName());
        order.setReceiverPhone(orderDto.getReceiverPhone());
        order.setRemark(orderDto.getRemark());

        order savedOrder = orderRepository.save(order);

        product.setStock(product.getStock() - orderDto.getQuantity());
        productRepository.save(product);

        return orderRepository.findByIdWithDetails(savedOrder.getId())
                .orElse(savedOrder);
    }

    public Optional<order> getOrderById(Integer id) {
        return orderRepository.findByIdWithDetails(id);
    }

    @Transactional
    public static order updateOrder(Integer id, orderUpdateDto orderDto) {
        Optional<order> orderOpt = orderRepository.findById(id);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }

        order order = orderOpt.get();
        Integer oldStatus = order.getStatus();
        Integer newStatus = orderDto.getStatus();

        if (newStatus != null) {
            validateStatusTransition(oldStatus, newStatus);
            order.setStatus(newStatus);

            if (newStatus == 2) {
                order.setCancelledAt(LocalDateTime.now());
                restoreStock(order);
            } else if (newStatus == 3) {
                order.setCompletedAt(LocalDateTime.now());
            } else if (newStatus == 1) {
                order.setPaymentTime(LocalDateTime.now());
            }
        }

        if (orderDto.getPaymentMethod() != null) {
            order.setPaymentMethod(orderDto.getPaymentMethod());
        }

        if (orderDto.getShippingAddress() != null) {
            order.setShippingAddress(orderDto.getShippingAddress());
        }

        if (orderDto.getReceiverName() != null) {
            order.setReceiverName(orderDto.getReceiverName());
        }

        if (orderDto.getReceiverPhone() != null) {
            order.setReceiverPhone(orderDto.getReceiverPhone());
        }

        if (orderDto.getRemark() != null) {
            order.setRemark(orderDto.getRemark());
        }

        return orderRepository.save(order);
    }

    public static List<order> getUserOrders(Integer userId) {
        if (!userRepository.existsById(userId)) {
            throw new RuntimeException("用户不存在");
        }

        return orderRepository.findByUserIdWithDetails(userId);
    }

    public static List<order> getAllOrders() {
        return orderRepository.findAll();
    }

    private String generateOrderNumber() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    private BigDecimal calculateShippingFee(BigDecimal weight, Integer quantity) {
        if (weight == null) {
            return BigDecimal.ZERO;
        }

        BigDecimal totalWeight = weight.multiply(new BigDecimal(quantity));
        if (totalWeight.compareTo(new BigDecimal("1")) <= 0) {
            return BigDecimal.ZERO;
        } else {
            return new BigDecimal("10.00");
        }
    }

    private void validateStatusTransition(Integer oldStatus, Integer newStatus) {
        if (oldStatus == 2 && newStatus != 2) {
            throw new RuntimeException("已取消的订单不能修改状态");
        }

        if (oldStatus == 3 && newStatus != 3) {
            throw new RuntimeException("已完成的订单不能修改状态");
        }
    }

    private void restoreStock(order order) {
        Optional<product> productOpt = productRepository.findById(order.getProductId());
        if (productOpt.isPresent()) {
            product product = productOpt.get();
            product.setStock(product.getStock() + order.getQuantity());
            productRepository.save(product);
        }
    }
}
